import { HttpException, Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import Redis from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class EmailService {
  constructor(
    @InjectRedis() private readonly redis: Redis,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  // 发送验证码
  async sendVerificationCode(email: string) {
    // 检查邮箱是否已注册
    const existUser = await this.userRepository.findOne({
      where: { email },
    });
    if (existUser) {
      throw new HttpException('该邮箱已被注册', 400);
    }

    // 生成6位随机验证码
    const code = Math.random().toString().slice(-6);

    // 将验证码存入 Redis，设置5分钟过期
    await this.redis.set(`verification:${email}`, code, 'EX', 300);

    // 发送验证码邮件
    const transporter = nodemailer.createTransport({
      host: 'smtp.qq.com',
      port: 587,
      secure: false,
      auth: {
        user: '2672852668@qq.com', // 替换为你的邮箱
        pass: 'fkswrergopcgdijf', // 替换为你的SMTP密码
      },
    });

    await transporter.sendMail({
      from: '2672852668@qq.com',
      to: email,
      subject: '注册验证码',
      text: `您的验证码是：${code}，有效期5分钟`,
    });

    return { message: '验证码已发送' };
  }
}
